import { unref } from 'vue';
import { defHttp } from '/@/utils/http/axios';
import { message } from 'ant-design-vue';

export const useApprovalMethods = (params: { getFormData: Function; approvalFindNextNodeUserUrl: string; taskId: any }) => {
  const onApprovalBeforeBtnClick = async (clickedBtn: {
    command_id: string;
    command_type: string;
    command_name: {
      zh: string;
      en: string;
      ja: string;
      locale: string;
    };
    command_policy_type: 'OPTIONAL';
    NEXT_NODE_USER;
    custom: number;
    isShowTip: boolean;
  }) => {
    const getFormData = params.getFormData;
    const approvalFindNextNodeUserUrl = params.approvalFindNextNodeUserUrl;
    const taskId = unref(params.taskId);

    const { command_id, command_type } = clickedBtn;
    return new Promise(async (reslove, reject) => {
      const res = await getFormData();
      // 判断点击的按钮是不是 需要审批人自选的，是的话，则提前收集好数据，并请求接口来获取审批人自选数据
      if (['OPTIONAL', 'NEXT_NODE_USER'].includes(clickedBtn.command_policy_type)) {
        const result = await defHttp.post(
          {
            url: approvalFindNextNodeUserUrl,
            params: {
              data: res,
              runTaskBo: { command_id, command_type, task_instance_id: taskId },
            },
          },
          { isTransformResponse: false }
        );
        if (result.code == 200) {
          reslove({
            command: 'selfSelectApprovalUsers',
            data: result.result,
          });
        } else {
          reject(result.message);
          message.error(result.message);
        }
      } else {
        reslove({});
      }
    });
  };

  return {
    onApprovalBeforeBtnClick,
  };
};
